package cn.edu.ctbu.websql.service;

import cn.edu.ctbu.websql.domain.Student;
import cn.edu.ctbu.websql.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;

@Service
public class StudentServer {

    @Autowired
    private StudentRepository studentRepository;

    //user_list
    public Page<Student> getAll(Pageable pageable){
        return studentRepository.findAll(pageable);
    }
    public List<Student> findAll(){
        return studentRepository.findAll();
    }
    public Student Insert(Student student){
        return studentRepository.save(student);
    }
    public void delete(Integer id) {
        studentRepository.deleteById(id);
    }
    public Optional<Student> getData(Integer id){
        return studentRepository.findById(id);
    }
    public Student update(Integer id,Student newStudent){
        Optional<Student> studentOptional = studentRepository.findById(id);
        if(studentOptional.isPresent()){

            Student student = studentOptional.get();
            student.setName(newStudent.getName());
            student.setPassword(newStudent.getPassword());
            student.setNo(newStudent.getNo());
            student.setSex(newStudent.getSex());
            student.setAge(newStudent.getAge());

            return studentRepository.save(student);
        }
        return null;
    }
    public List<Student> searchData(String no){
        return studentRepository.findAllByNoLike(no+"%");
    }

    //user_login
    public List<Student> findByNoAndPassword(String username,String password){
        return studentRepository.findByNoAndPassword(username,password);
    }

}
